import {
  Controller,
  Get,
  Post,
  Query,
  Render,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';
import * as sharp from 'sharp'; // 压缩文件
import * as fs from 'fs';
import { CosService } from 'src/shared/services/cos.service';
@Controller('admin')
export class UploadController {
  constructor(private readonly cosService: CosService) {}
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('upload', {
      // upload是前端接收参数名
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          // path.extname 提取文件扩展名
          const filename = uuidv4() + path.extname(file.originalname);
          callback(null, filename);
        },
      }),
      fileFilter: (req, file, callback) => {
        if (!file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
          return callback(new Error('不支持的文件类型'), false);
        }
        callback(null, true);
      },
    }),
  )
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    const filename = `${path.basename(file.filename, path.extname(file.filename))}.min.jpeg`;
    const outputFilePath = `./uploads/${filename}`;
    await sharp(file.path)
      .resize(800, 600, {
        fit: sharp.fit.inside,
        withoutEnlargement: true,
      })
      .toFormat('jpeg')
      .toFile(outputFilePath);
    // fs.unlinkSync(file.path); // 删除原始文件
    // 	nest-1316737134.cos.ap-guangzhou.myqcloud.com
    //https://nest-1316737134.cos.ap-guangzhou.myqcloud.com/%E8%81%94%E6%83%B3%E6%88%AA%E5%9B%BE_20241208203325.png
    return {
      url: `/uploads/${filename}`,
    };
  }
  @Get('cos-signature')
  async getCosSignature(@Query('key') key: string) {
    return this.cosService.getAuth(key, 60);
  }
}
